package com.fujifilm.project.plan.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.fujifilm.project.plan.entity.ProjectGroup;
import com.fujifilm.project.plan.entity.table.ProjectGroupTableDef;
import com.fujifilm.project.plan.error.BusinessException;
import com.fujifilm.project.plan.mapper.ProjectGroupMapper;
import com.fujifilm.project.plan.service.IProjectGroupService;
import com.fujifilm.project.plan.vo.request.RequestRecords.ProjectGroupPageListRequest;
import com.fujifilm.project.plan.vo.request.RequestRecords.ProjectGroupSaveRequest;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@RequiredArgsConstructor
public class ProjectGroupServiceImpl implements IProjectGroupService {
    private final ProjectGroupMapper projectGroupMapper;

    @Override
    public Page<ProjectGroup> pageList(ProjectGroupPageListRequest req) {
        log.info("Fetching project group page list with request: {}", req);
        if (req == null) {
            log.error("Request cannot be null");
            throw new IllegalArgumentException("Request cannot be null");
        }

        QueryWrapper queryWrapper = QueryWrapper.create()
                .from(ProjectGroupTableDef.PROJECT_GROUP)
                .where(ProjectGroupTableDef.PROJECT_GROUP.IS_DELETED.eq(0));

        if (req.filter() != null && !req.filter().isEmpty()) {
            queryWrapper = queryWrapper
                    .and(ProjectGroupTableDef.PROJECT_GROUP.GROUP_NAME.like(req.filter()))
                    .or(ProjectGroupTableDef.PROJECT_GROUP.GROUP_CODE.like(req.filter()));
        }

        Page<ProjectGroup> res = projectGroupMapper.paginate(req.page(), req.size(), queryWrapper);
        // convert to vo class if needed
        return res;
    }

    @Override
    public void save(ProjectGroupSaveRequest req) throws BusinessException {
        if (req.id() <= 0) {
            // add
            ProjectGroup projectGroup = new ProjectGroup();
            projectGroup.setGroupName(req.groupName());
            projectGroup.setGroupCode(req.groupCode());
            projectGroup.setBelongToGroup(req.belongToGroup());
            projectGroup.setBelongToCustomer(req.belongToCustomer());
            projectGroup.setGeneralDepartment(req.generalDepartment());
            projectGroup.setDepartment(req.department());
            projectGroup.setStatus(req.status());

            int rows = projectGroupMapper.insertSelective(projectGroup);
            if (rows <= 0) {
                log.error("Failed to insert new project group with name: {}", req.groupName());
                throw BusinessException.of("Failed to create project group");
            }

            return;
        }

        // update
        // Check if the project group exists
        ProjectGroup existingGroup = projectGroupMapper.selectOneById(req.id());
        if (existingGroup == null) {
            log.error("Project group with ID {} does not exist", req.id());
            throw BusinessException.of("Project group does not exist");
        }
        ProjectGroup projectGroup = new ProjectGroup();
        projectGroup.setId(req.id());
        projectGroup.setGroupName(req.groupName());
        projectGroup.setGroupCode(req.groupCode());
        projectGroup.setBelongToGroup(req.belongToGroup());
        projectGroup.setBelongToCustomer(req.belongToCustomer());
        projectGroup.setGeneralDepartment(req.generalDepartment());
        projectGroup.setDepartment(req.department());
        projectGroup.setStatus(req.status());

        int rows = projectGroupMapper.update(projectGroup);
        if (rows <= 0) {
            log.error("Failed to update project group with ID: {}", req.id());
            throw BusinessException.of("Failed to update project group");
        }
    }

    @Override
    public void delete(long id) throws BusinessException {
        int rows = projectGroupMapper.deleteById(id);
        if (rows <= 0) {
            log.info("Failed to delete project group with ID: {}", id);
        }
    }

    @Override
    public void batchDelete(List<Long> ids) throws BusinessException {
        int rows = projectGroupMapper.deleteBatchByIds(ids);
        if (rows <= 0) {
            log.info("Failed to batch delete project groups with IDs: {}", ids);
        }
    }

    @Override
    public ProjectGroup info(long id) throws BusinessException {
        ProjectGroup projectGroup = projectGroupMapper.selectOneById(id);
        if (projectGroup == null) {
            log.error("Project group with ID {} does not exist", id);
            throw BusinessException.of("Project group does not exist");
        }
        return projectGroup;
    }

}
